/*
 * XEclipseHelpLibrary.java
 * 
 * Copyright (c) 2006 - 2007
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.xfc.help;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import nu.xom.Element;
import nu.xom.Elements;

/**
 * 
 * 
 * @author Devon Carew
 */
class XEclipseHelpLibrary
	extends XHelpLibrary
{

	public XEclipseHelpLibrary(File jarFile)
		throws IOException
	{
		super(jarFile);
	}
	
	public String parseTitle()
		throws IOException
	{
		Element tocElement = parseXMLEntry("toc.xml");
		
		return tocElement.getAttributeValue("label");
	}
	
	protected XTableOfContents parseTableOfContents()
		throws IOException
	{
		Element 	tocElement = parseXMLEntry("toc.xml");
		
		XTableOfContents 	contents = new XTableOfContents(tocElement.getAttributeValue("label"));
		contents.setLocation(tocElement.getAttributeValue("href"));
		
		Elements topics = tocElement.getChildElements("topic");
		
		for (int i = 0; i < topics.size(); i++)
		{
			Element topicElement = topics.get(i);
			
			contents.getChildren().add(parseTopic(topicElement));
		}
		
		return contents;
	}
	
	private XContentsItem parseTopic(Element element)
		throws IOException
	{
		XContentsItem item = new XContentsItem(element.getAttributeValue("label"));
		
		item.setLocation(element.getAttributeValue("href"));
		
		Elements children = element.getChildElements();
		
		for (int i = 0; i < children.size(); i++)
		{
			Element child = children.get(i);
			
			if ("topic".equals(child.getLocalName()))
			{
				item.getChildren().add(parseTopic(child));
			}
			else if ("link".equals(child.getLocalName()))
			{
				String tocLocation = child.getAttributeValue("toc");
				
				XContentsItem linkToc = parseSubTopic(tocLocation);
				
				// Eclipse gracefully handles missing subtopics, so we should too.
				if (linkToc != null)
					item.getChildren().addAll(linkToc.getChildren());
			}
		}
		
		return item;
	}
	
	private XContentsItem parseSubTopic(String entryName)
		throws IOException
	{
		try
		{
			Element element = parseXMLEntry(entryName);
			
			return parseTopic(element);
		}
		catch (FileNotFoundException fnfe)
		{
			// Missing file in Eclipse help library.
			
			return null;
		}
	}
	
}
